import React, { useEffect, useRef, useState } from 'react';
import { Card, Typography, Button, Space } from 'antd';
import { BoldOutlined, ItalicOutlined, UnderlineOutlined, OrderedListOutlined, UnorderedListOutlined, UndoOutlined, RedoOutlined, StrikethroughOutlined, LinkOutlined, FontSizeOutlined, AlignLeftOutlined, AlignCenterOutlined, AlignRightOutlined } from '@ant-design/icons';
// @ts-ignore
import Squire from 'squire-rte';
// @ts-ignore
import DOMPurify from 'dompurify';

const { Title, Paragraph } = Typography;

// 声明全局 DOMPurify 类型
declare global {
  interface Window {
    DOMPurify: any;
  }
}

const SquirePage: React.FC = () => {
  const editorRef = useRef<HTMLDivElement>(null);
  const squireRef = useRef<any>(null);
  const [content, setContent] = useState('');

  useEffect(() => {
    if (editorRef.current && !squireRef.current) {
      // 确保 DOMPurify 在全局可用
      if (typeof window !== 'undefined') {
        window.DOMPurify = DOMPurify;
      }
      
      squireRef.current = new Squire(editorRef.current, {
        blockTag: 'P',
        blockAttributes: {},
        tagAttributes: {
          blockquote: {},
          ul: {},
          ol: {},
          li: {},
          a: { target: '_blank' }
        }
      });

      // 设置初始内容
      squireRef.current.setHTML('<p>这是 Squire 编辑器的初始内容。您可以在这里输入文本并使用工具栏进行格式化。</p>');
      
      // 监听内容变化
      squireRef.current.addEventListener('input', () => {
        setContent(squireRef.current.getHTML());
      });
    }

    return () => {
      if (squireRef.current) {
        squireRef.current.destroy();
        squireRef.current = null;
      }
    };
  }, []);

  const handleBold = () => {
    squireRef.current?.bold();
  };

  const handleItalic = () => {
    squireRef.current?.italic();
  };

  const handleUnderline = () => {
    squireRef.current?.underline();
  };

  const handleOrderedList = () => {
    squireRef.current?.makeOrderedList();
  };

  const handleUnorderedList = () => {
    squireRef.current?.makeUnorderedList();
  };

  const handleUndo = () => {
    squireRef.current?.undo();
  };

  const handleRedo = () => {
    squireRef.current?.redo();
  };

  const handleStrikethrough = () => {
    squireRef.current?.strikethrough();
  };

  const handleLink = () => {
    const url = prompt('请输入链接地址:');
    if (url) {
      squireRef.current?.makeLink(url);
    }
  };

  const handleRemoveLink = () => {
    squireRef.current?.removeLink();
  };

  const handleAlignLeft = () => {
    squireRef.current?.setTextAlignment('left');
  };

  const handleAlignCenter = () => {
    squireRef.current?.setTextAlignment('center');
  };

  const handleAlignRight = () => {
    squireRef.current?.setTextAlignment('right');
  };

  const handleIncreaseQuoteLevel = () => {
    squireRef.current?.increaseQuoteLevel();
  };

  const handleDecreaseQuoteLevel = () => {
    squireRef.current?.decreaseQuoteLevel();
  };

  const handleGetContent = () => {
    const html = squireRef.current?.getHTML();
    console.log('Squire content:', html);
    console.log('Plain text:', squireRef.current?.getTextContent());
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Title level={2}>Squire 富文本编辑器</Title>
        <Paragraph>
          Squire 是一个轻量级的富文本编辑器，专注于提供简洁的编辑体验和高性能。
        </Paragraph>
        
        <div style={{ marginTop: '20px' }}>
          <div style={{ marginBottom: '16px' }}>
            <Space style={{ marginBottom: '8px', flexWrap: 'wrap' }}>
              <Button
                onClick={handleBold}
                icon={<BoldOutlined />}
                size="small"
              >
                粗体
              </Button>
              <Button
                onClick={handleItalic}
                icon={<ItalicOutlined />}
                size="small"
              >
                斜体
              </Button>
              <Button
                onClick={handleUnderline}
                icon={<UnderlineOutlined />}
                size="small"
              >
                下划线
              </Button>
              <Button
                onClick={handleStrikethrough}
                icon={<StrikethroughOutlined />}
                size="small"
              >
                删除线
              </Button>
              <Button
                onClick={handleLink}
                icon={<LinkOutlined />}
                size="small"
              >
                插入链接
              </Button>
            </Space>
            <Space style={{ marginBottom: '8px', flexWrap: 'wrap' }}>
              <Button
                onClick={handleAlignLeft}
                icon={<AlignLeftOutlined />}
                size="small"
              >
                左对齐
              </Button>
              <Button
                onClick={handleAlignCenter}
                icon={<AlignCenterOutlined />}
                size="small"
              >
                居中
              </Button>
              <Button
                onClick={handleAlignRight}
                icon={<AlignRightOutlined />}
                size="small"
              >
                右对齐
              </Button>
              <Button
                onClick={handleIncreaseQuoteLevel}
                size="small"
              >
                增加引用
              </Button>
              <Button
                onClick={handleDecreaseQuoteLevel}
                size="small"
              >
                减少引用
              </Button>
            </Space>
            <Space style={{ flexWrap: 'wrap' }}>
              <Button
                onClick={handleUnorderedList}
                icon={<UnorderedListOutlined />}
                size="small"
              >
                无序列表
              </Button>
              <Button
                onClick={handleOrderedList}
                icon={<OrderedListOutlined />}
                size="small"
              >
                有序列表
              </Button>
              <Button
                onClick={handleUndo}
                icon={<UndoOutlined />}
                size="small"
              >
                撤销
              </Button>
              <Button
                onClick={handleRedo}
                icon={<RedoOutlined />}
                size="small"
              >
                重做
              </Button>
            </Space>
          </div>
          
          <div
            ref={editorRef}
            style={{
              border: '1px solid #d9d9d9',
              borderRadius: '6px',
              padding: '12px',
              minHeight: '300px',
              fontSize: '14px',
              lineHeight: '1.6',
              outline: 'none'
            }}
          />
        </div>
        
        <div style={{ marginTop: '20px' }}>
          <Button onClick={handleGetContent}>获取内容</Button>
        </div>
      </Card>
    </div>
  );
};

export default SquirePage;